package io.renren.modules.report.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.annotation.NoValidation;
import io.renren.common.utils.ConfigConstant;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.TestFileUtil;
import io.renren.modules.report.service.ReportService;
import io.renren.modules.report.vo.FillData;
import io.renren.modules.work.entity.ScConsumablesEntity;
import io.renren.modules.work.entity.ScGoodsEntity;
import io.renren.modules.work.entity.ScProjectEntity;
import io.renren.modules.work.entity.ScProjectdtlEntity;
import io.renren.modules.work.service.ScConsumablesService;
import io.renren.modules.work.service.ScGoodsService;
import io.renren.modules.work.service.ScProjectService;
import io.renren.modules.work.service.ScProjectdtlService;
import io.renren.vo.ReportVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.data.JRMapCollectionDataSource;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;

@RestController
@RequestMapping("/report")
@Api("报表测试接口")
public class ReportController {
    @Autowired
    private ReportService reportService;





    @ApiOperation("业务申请单PDF预览")
    @GetMapping("/showPdf")
    @NoValidation
    public void showPdf(HttpServletResponse response, @RequestParam String businessUuid)throws Exception{
        reportService.optPdf(response,businessUuid,1);
    }

    @ApiOperation("业务申请单PDF下载")
    @GetMapping("/downPdf")
    @NoValidation
    public void downPdf(HttpServletResponse response,@RequestParam String businessUuid)throws Exception{
        reportService.optPdf(response,businessUuid,2);
    }




    /**
     * 器材消耗单
     */
    @PostMapping("/goodsConsumeReport")
    private void goodsConsumeReport(HttpServletResponse response,@RequestBody ReportVo reportVo) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/pdf");
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("test", "UTF-8") + ".pdf");

        try (OutputStream outputStream = response.getOutputStream()) {
            JasperPrint jasperPrint = reportService.goodsConsumeReport(reportVo.getId(), reportVo.getReportName());
            JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
        } catch (IOException | JRException e) {
            e.printStackTrace();
        }
    }

    /**
     * 完工验收单
     */
    @PostMapping("/rgchkReport")
    private void rgchkReport(HttpServletResponse response,@RequestBody ReportVo reportVo) throws Exception{
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/pdf");
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("test", "UTF-8") + ".pdf");
        try (OutputStream outputStream = response.getOutputStream()) {
            JasperPrint jasperPrint = reportService.rgchkReport(reportVo.getId(), reportVo.getReportName());
            JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
        } catch (IOException | JRException e) {
            e.printStackTrace();
        }
    }

    /**
     * 工程审价单
     */
    @PostMapping("/priceReviewReport")
    private void priceReviewReport(HttpServletResponse response,@RequestBody ReportVo reportVo) throws Exception{
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/pdf");
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("test", "UTF-8") + ".pdf");
        try (OutputStream outputStream = response.getOutputStream()) {
            JasperPrint jasperPrint = reportService.priceReviewReport(reportVo.getId(), reportVo.getReportName());
            JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
        } catch (IOException | JRException e) {
            e.printStackTrace();
        }
    }
    /**
     * 工程报价单
     */
    @PostMapping("/quotationReport")
    private void quotationReport(HttpServletResponse response,@RequestBody ReportVo reportVo) throws Exception{
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/pdf");
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("test", "UTF-8") + ".pdf");
        try (OutputStream outputStream = response.getOutputStream()) {
            JasperPrint jasperPrint = reportService.quotationReport(reportVo.getId(), reportVo.getReportName());
            JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
        } catch (IOException | JRException e) {
            e.printStackTrace();
        }
    }
    /**
     * 工人登记单
     */
    @PostMapping("/workerReport")
    private void workerReport(HttpServletResponse response,@RequestBody ReportVo reportVo) throws Exception{
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/pdf");
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("test", "UTF-8") + ".pdf");
        try (OutputStream outputStream = response.getOutputStream()) {
            JasperPrint jasperPrint = reportService.workerReport(reportVo.getId(), reportVo.getReportName());
            JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
        } catch (IOException | JRException e) {
            e.printStackTrace();
        }
    }
    /**
     * 咨询单
     */
    @PostMapping("/askReport")
    private void askReport(HttpServletResponse response,@RequestBody ReportVo reportVo) throws Exception{
        response.setCharacterEncoding("utf-8");
        //response.setContentType("application/pdf");
       // response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("test", "UTF-8") + ".pdf");
        response.setHeader("Content-Disposition", "attachment;filename=first.xls");
        response.setContentType("application/vnd_ms-excel");
        try (OutputStream outputStream = response.getOutputStream()) {
            JasperPrint jasperPrint = reportService.askReport(reportVo.getId(), reportVo.getReportName());
           // JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
            JRXlsExporter exporter=new JRXlsExporter();
            exporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, response.getOutputStream());
            exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
            exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
            exporter.exportReport();
        } catch (IOException | JRException e) {
            e.printStackTrace();
        }
    }



    /**
     * testEXCEL
     */
    @PostMapping("testExcel")
    private void testExcel(HttpServletResponse response,@RequestBody ReportVo reportVo)throws Exception{
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=first.xlsx");
        try (OutputStream outputStream = response.getOutputStream()) {
            String templateFileName =
                    TestFileUtil.getPath() + "excelTemplate" +  File.separator + "complexFillWithTable.xlsx";
            ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(templateFileName).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            HashMap<String, Object> map = new HashMap<>();
            map.put("date", "2019年10月9日13:28:28");
            map.put("total", 1000);
            excelWriter.fill(map, fillConfig, writeSheet);
            excelWriter.fill(data(), fillConfig, writeSheet);
            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 维修前后图片
     */
    @PostMapping("/picReport")
    private void picReport(HttpServletResponse response,@RequestBody ReportVo reportVo) throws Exception{
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/pdf");
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("test", "UTF-8") + ".pdf");
        try (OutputStream outputStream = response.getOutputStream()) {
            JasperPrint jasperPrint = reportService.picReport(reportVo.getId(), reportVo.getReportName());
            JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
        } catch (IOException | JRException e) {
            e.printStackTrace();
        }
    }
    private List<FillData> data() {
        List<FillData> list = ListUtils.newArrayList();
        for (int i = 0; i < 10; i++) {
            FillData fillData = new FillData();
            list.add(fillData);
            fillData.setName("张三");
            fillData.setNumber(5.2);
            fillData.setDate(new Date());
        }
        return list;
    }


    /**
     * 打印器材消耗excel
     */
    @PostMapping("/goodsConsumeExcel")
    public void goodsConsumeExcel(HttpServletResponse response,@RequestBody ReportVo reportVo)throws Exception{
        String fileName = DateUtils.format(new Date(),"yyyyMMddHHmmss")+"器材消耗单.xlsx";
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("content-disposition",
                "attachment;fileName="+java.net.URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader("Access-Control-Expose-Headers","content-disposition");

        try (OutputStream outputStream = response.getOutputStream()) {
            //服务器环境下
            ClassPathResource template = new ClassPathResource("excelTemplate"+File.separator+"goodsConsume.xlsx");
            InputStream templateInputStream = template.getInputStream();
            //本地开发环境下
//            String templateFileName =
//                    TestFileUtil.getPath() + "excelTemplate" +  File.separator + "goodsConsume.xlsx";
            ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(templateInputStream).build();
            reportService.goodsConsumeExcel(reportVo.getId(),reportVo.getReportName(),excelWriter);
            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();

        }
    }

    /**
     * 完工验收单
     */
    @PostMapping("/rgchkExcel")
    public void rgcheckExcel(HttpServletResponse response,@RequestBody ReportVo reportVo)throws Exception{
        String fileName = DateUtils.format(new Date(),"yyyyMMddHHmmss")+"完工验收单.xlsx";
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("content-disposition",
                "attachment;fileName="+java.net.URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader("Access-Control-Expose-Headers","content-disposition");

        try (OutputStream outputStream = response.getOutputStream()) {
            //服务器环境下
            ClassPathResource template = new ClassPathResource("excelTemplate"+File.separator+"rgchk.xlsx");
            InputStream templateInputStream = template.getInputStream();
            //本地开发环境下
//            String templateFileName =
//                    TestFileUtil.getPath() + "excelTemplate" +  File.separator + "rgchk.xlsx";
            ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(templateInputStream).build();
            reportService.rgchkExcel(reportVo.getId(),reportVo.getReportName(),excelWriter);
            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();

        }
    }

    /**
     * 工程审价单
     */
    @PostMapping("/priceReviewExcel")
    public void priceReviceExcel(HttpServletResponse response,@RequestBody ReportVo reportVo)throws Exception{

        String fileName = DateUtils.format(new Date(),"yyyyMMddHHmmss")+"工程审价单.xlsx";
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("content-disposition",
                "attachment;fileName="+java.net.URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader("Access-Control-Expose-Headers","content-disposition");

        try (OutputStream outputStream = response.getOutputStream()) {
            //服务器环境下
            ClassPathResource template = new ClassPathResource("excelTemplate"+File.separator+"priceReview.xlsx");
            InputStream templateInputStream = template.getInputStream();
            //本地开发环境下
//            String templateFileName =
//                    TestFileUtil.getPath() + "excelTemplate" +  File.separator + "priceReview.xlsx";
            ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(templateInputStream).build();
            reportService.priceReview(reportVo.getId(),reportVo.getReportName(),excelWriter);
            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();

        }
    }
}
